<?php
/**
 * Created by PhpStorm.
 * User: luxuewen_gz
 * Date: 2018/12/29
 * Time: 8:45
 */

namespace app\admin\logic;

use app\admin\validate\Permission as PermissionValidate;

class Permission
{
    public function getAll(){
        $permissionMenu = model('PermissionMenu')->where('is_delete', 'eq', 0)
            ->field('menu_id,permission_id')->select()->toArray();
        $permissionMenu = array_column($permissionMenu, 'permission_id', 'menu_id');
        $menu = (new Menu())->getAll()->toArray();
        foreach ($menu as $k => $v) {
            $menu[$k]['permission_id'] = $permissionMenu[$v['id']];
            foreach ($v['second'] as $ks => $vs) {
                $menu[$k]['second'][$ks]['permission_id'] = $permissionMenu[$vs['id']];
            }
        }
        return $menu;
    }
    public function getAllWithRoleEdit($data){
        $validate = new PermissionValidate;
        $result = $validate->scene('roleEdit')->check($data);
        if(!$result){
            exception($validate->getError());
        }
        $where[] = ['is_delete', 'eq', 0];
        $where[] = ['role_id', 'eq', $data['role_id']];
        $permissionMenu = model('PermissionMenu')->where('is_delete', 'eq', 0)
            ->field('menu_id,permission_id')->select()->toArray();
        $permissionMenu = array_column($permissionMenu, 'permission_id', 'menu_id');
        $menu = (new Menu())->getAll()->toArray();
        $role_permission = model('RolePermission')->where($where)->field('permission_id')->select()->toArray();
        $role_permission = array_column($role_permission, 'permission_id');
        foreach ($menu as $k => $v) {
            $menu[$k]['permission_id'] = $permissionMenu[$v['id']];
            $menu[$k]['selected'] = false;
            if (in_array($menu[$k]['permission_id'], $role_permission)) {
                $menu[$k]['selected'] = true;
            }
            foreach ($v['second'] as $ks => $vs) {
                $menu[$k]['second'][$ks]['permission_id'] = $permissionMenu[$vs['id']];
                $menu[$k]['second'][$ks]['selected'] = false;
                if (in_array($menu[$k]['second'][$ks]['permission_id'], $role_permission)) {
                    $menu[$k]['second'][$ks]['selected'] = true;
                }
                foreach ($vs['third'] as $kt => $vt) {
                    $menu[$k]['second'][$ks]['third'][$kt]['permission_id'] = $permissionMenu[$vt['id']];
                    $menu[$k]['second'][$ks]['third'][$kt]['selected'] = false;
                    if (in_array($menu[$k]['second'][$ks]['third'][$kt]['permission_id'], $role_permission)) {
                        $menu[$k]['second'][$ks]['third'][$kt]['selected'] = true;
                    }
                }
            }
        }
        return $menu;
    }


}